<template>
  <div
    :class="prefixCls"
    :style="{
      width: boxWidth,
    }"
    class="relative"
  >
    <Spin wrapperClassName="h-full" :spinning="loading">
      <FormTitle :text="formTitle">
        <template #extra>
          <ButtonActions @edit="handleEdit" v-if="buttons" :data="buttons" />
        </template>
      </FormTitle>
      <div class="py-4 px-2" :style="{ padding: formPadding }">
        <BasicForm @register="registerForm" v-if="!refresh"
      /></div>
    </Spin>
    <ModelDesign :classify="2" :modelId="modelId" @success="init" />
    <FormModal :isCustom="true" @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup name="ComModelFormPage">
  import { ref, unref, watch, onMounted, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Spin } from 'ant-design-vue';
  import FormModal from '/@/components/ModelTable/src/components/FormModal.vue';

  import FormTitle from '/@/components/HFormTitle';
  import ButtonActions from '/@/components/ModelTable/src/components/ButtonActions.vue';
  import ModelDesign from '/@/components/ModelTable/src/components/ShowModelDesign.vue';

  // import { ScrollContainer } from '/@/components/Container/index';
  import { UseModalInit } from '/@/components/ModelTable/src/hooks/useComFormModel';
  import { getRowKeys } from '/@/components/ModelTable/src/hooks/functionSet';
  import { useDebounceFn } from '@vueuse/core';

  import { ModalParams } from '/@/components/ModelTable';
  import { getCSSValue, sleep } from '/@/utils';

  import { useDesign } from '/@/hooks/web/useDesign';
  import { isUnDef } from '/@/utils/is';
  import { commonGetModelIdByIdApi, getModuleFormInfoApi } from '/@/api/config-center/model-design';
  import QueryString from 'qs';
  import { useModal } from '/@/components/Modal';

  const { prefixCls } = useDesign('ComModelFormPage');
  const loading = ref(true);
  const refresh = ref(false);

  const [registerForm, formActionType] = useForm({
    disabled: true,
    baseColProps: { span: 23 },
    showActionButtonGroup: false,
  });
  const { resetFields } = formActionType;
  const props = withDefaults(
    defineProps<{
      modalParams?: ModalParams;
    }>(),
    {
      modalParams: () => ({}),
    },
  );
  const modelId = ref(props.modalParams.modelId);
  const delyReload = useDebounceFn(init, 100);
  const formTitle = ref();
  const formPadding = ref();
  const boxWidth = ref();

  const buttons = ref();
  watch(
    () => props.modalParams,
    ({ modelId: moId }) => {
      if (moId) {
        modelId.value = moId;
        nextTick(() => {
          delyReload();
        });
      }
    },
  );
  let btnData: any = {};
  async function init() {
    resetFields();

    const {
      preview,
      detail,
      isUpdate,
      record = {},
      query,
      param,
      parentQuery,
      parentParam,
      moduleId,
    } = props.modalParams;

    const queryString = Object.assign(
      QueryString.parse(parentQuery || '', {
        ignoreQueryPrefix: true,
      }),
      QueryString.parse(query || '', {
        ignoreQueryPrefix: true,
      }),
    );

    btnData = {
      dataModelId: unref(modelId),
      moduleId,
      isUpdate: isUpdate || parentQuery || query,
      readonly: true,
      params: queryString,
    };

    if (isUpdate) {
      const pRet = getRowKeys(parentParam || '', record);
      const selfParam = getRowKeys(param || '', record);

      const mergeParam = Object.assign(pRet, selfParam);

      Object.keys(mergeParam).forEach((key) => {
        if (isUnDef(mergeParam[key])) {
          delete mergeParam[key];
        }
      });
      btnData.params = Object.assign(record, btnData.params, mergeParam);
    }

    try {
      let formConfig: any = {};

      if (!preview && !detail) {
        const { formDesignInfo } = await getModuleFormInfoApi({
          moduleId,
          modelId: unref(modelId),
        });

        formConfig = formDesignInfo;
      }

      const modalInit = new UseModalInit(
        { btnData, formDesignInfo: formConfig, apiFn: commonGetModelIdByIdApi },
        formActionType,
      );

      const { btns = [], title, width, padding, value } = await modalInit.initialize();
      formTitle.value = title;

      buttons.value = btns.map((el) => Object.assign(el, btnData.params, value));

      formPadding.value = getCSSValue(padding, '0');
      boxWidth.value = getCSSValue(width, '100%');
    } finally {
      loading.value = false;
    }
  }

  onMounted(() => {
    init();
  });

  const [registerModal, { openModal, setModalProps }] = useModal();
  async function handleSuccess() {
    refresh.value = true;
    await sleep();
    refresh.value = false;
    loading.value = true;
    await init();
  }
  function handleEdit(btnItem) {
    const { params, moduleId, dataModelId } = btnData;
    console.log(btnItem, btnData);

    setModalProps({ width: '60%', destroyOnClose: true });
    openModal(true, { params, moduleId, dataModelId, isUpdate: true });
  }
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-ComModelFormPage';

  .@{prefix-cls} {
    padding: 16px 8px 16px;
    height: 100%;
    background-color: @component-background;

    .vben-basic-form {
      &[disabled='true'] {
        .ant-form-item-label {
          label {
            color: @text-color-call-out;
          }
        }
      }

      [class*='-selector'],
      [class*='-disabled'] {
        color: #333 !important;
        cursor: auto !important;
        border: transparent !important;
        background-color: transparent !important;

        input {
          cursor: auto !important;
        }

        [class*='select-arrow'],
        [class*='picker-suffix'],
        [class*='-separato'] {
          display: none;
        }
      }
    }
  }
</style>
